//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.example.controller;

import cn.hutool.core.io.FileUtil;
import com.example.common.Result;
import com.example.exception.CustomException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.annotation.Resource;
import com.example.entity.ClubImage;
import com.example.mapper.ClubImageMapper;

@RestController
@RequestMapping({"/files"})
public class FileController {
    // 使用相对路径，存储在项目根目录下的 files 文件夹中
    private static final String filePath = System.getProperty("user.dir") + "/files/";
    // 定义文件大小限制为 10MB
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    @Resource
    private ClubImageMapper clubImageMapper;

    public FileController() {
        // 确保文件存储目录存在
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
    }

    /**
     * 文件上传接口
     */
    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file,
                                     @RequestParam(value = "clubId", required = false) Integer clubId,
                                     @RequestParam(value = "uploaderId", required = false) Integer uploaderId) {
        try {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return createErrorResponse("文件名不能为空");
            }

            // 检查文件大小
            if (file.getSize() > MAX_FILE_SIZE) {
                return createErrorResponse("文件大小不能超过 10 MB");
            }

            String fileName = System.currentTimeMillis() + "_" + originalFilename;
            String realPath = filePath + fileName;

            FileUtil.writeBytes(file.getBytes(), realPath);

            String url = "http://localhost:8080/files/wang/download/" + fileName;
            return createSuccessResponse(url);
        } catch (Exception e) {
            return createErrorResponse("上传失败：" + e.getMessage());
        }
    }

    /**
     * 文件下载接口
     */
    @GetMapping("/wang/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) {
        try {
            String realPath = filePath + fileName;
            if (!FileUtil.exist(realPath)) {
                throw new CustomException("404", "文件不存在");
            }

            // 设置响应头，允许图片直接显示
            response.setContentType("image/*");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "max-age=31536000");

            OutputStream os = response.getOutputStream();
            byte[] bytes = FileUtil.readBytes(realPath);
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            throw new CustomException("500", "文件下载失败：" + e.getMessage());
        }
    }

    @PostMapping("/wang/upload")
    public Map<String, Object> wangEditorUpload(MultipartFile file,
                                             @RequestParam(value = "clubId") Integer clubId,
                                             @RequestParam(value = "uploaderId", required = false) Integer uploaderId) {
        try {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return createErrorResponse("文件名不能为空");
            }

            // 检查文件大小
            if (file.getSize() > MAX_FILE_SIZE) {
                return createErrorResponse("文件大小不能超过 10 MB");
            }

            // 检查必要参数
            if (uploaderId == null) {
                return createErrorResponse("上传者ID不能为空");
            }

            String fileName = System.currentTimeMillis() + "_" + originalFilename;
            String realPath = filePath + fileName;

            FileUtil.writeBytes(file.getBytes(), realPath);

            String url = "http://localhost:8080/files/wang/download/" + fileName;
            // 保存到数据库
            ClubImage image = new ClubImage();
            image.setImageUrl(url);
            image.setUploadTime(new Date());
            if (clubId != null) {
                image.setClubId(clubId);
            }
            image.setUploaderId(uploaderId); // 直接设置，因为我们已经检查过它不为空
            clubImageMapper.insert(image);
            return createWangSuccessResponse(url);
        } catch (Exception e) {
            return createErrorResponse("上传失败：" + e.getMessage());
        }
    }

    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String url) {
        Map<String, Object> result = new HashMap<>();
        result.put("errno", 0);
        Map<String, String> data = new HashMap<>();
        data.put("url", url);
        result.put("data", data);
        return result;
    }

    /**
     * 创建 WangEditor 成功响应
     */
    private Map<String, Object> createWangSuccessResponse(String url) {
        Map<String, Object> resMap = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> urlMap = new HashMap<>();
        urlMap.put("url", url);
        list.add(urlMap);
        resMap.put("errno", 0);
        resMap.put("data", list);
        return resMap;
    }

    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("errno", 1);
        error.put("message", message);
        return error;
    }
}